class Category < ActiveRecord::Base
  validates :name, presence: true
  validates :slug, uniqueness: true

  has_many :articles, -> { where.not(published_at: nil) }, foreign_key: :category_id

  private
  after_destroy :set_articles_category_to_nil
  def set_articles_category_to_nil
    Article.where(category_id: id).update_all category_id: nil
  end

  before_save :reset_slug
  def reset_slug
    self.slug = nil if name_changed?
  end

  after_save :translate_name_when_change
  def translate_name_when_change
    delay.translate_name if name_changed?
  end

  def translate_name
    text_translator = Termit::TextTranslator.new source_lang: 'zh', target_lang: 'en', text: name
    slug = text_translator.call
    update slug: slug.gsub(/\s+/, '-').downcase
  end

  def self.recount(*category_ids)
    @categories = Category.find category_ids.compact
    @categories.each do |category|
      category.update count: category.articles.count
    end
  end
end
